/**
 * 该对象用来定义界面常用的JS工具函数.
 */
function WinUtil(){}

/**
 * 在页面中打开一个对话框
 * @param control 对话框内容
 * @param option
 *      - title 对话框标题
 *      - keyboard 默认true,支持esc关闭对话框
 *      - backdrop 默认支持遮罩层，点击遮罩层外关闭对话框  [false:无遮罩层] ['static':有遮罩层，点击遮罩层外不关闭对话框]
 *      - close 默认true ,有关闭图标
 *      - type 默认中型对话框, [large:大对话框][small:小对话框]
 *      - width 对话框宽度
 *      - headerable 是否显示头部
 *      - opacity 对话框透明度
 * @param onshow 显示对话框回调方法
 * @param onclose 关闭对话框回调方法
 * @param onbeforeshow 显示对话框前回调方法
 * @param onbeforehide 关闭对话框前回调方法
 */
WinUtil.openDialog = function(control, option, onshow, onclose,onbeforeshow,onbeforehide) {
	application.getHandleClass().postMessage({id:"MSG_MAPPAGE_CLEARTARGET"});//地图页面弹窗
    var template = "<div class='modal fade' tabindex='-1' role='dialog'>" +
                        "<div class='modal-dialog' role='document'>" +
                            "<div class='modal-content'>" +
                                "<div class='modal-header'>" +
                                    "<h5 class='modal-title' style='color:#fff'></h5>" +
                                "</div>" +
                            "</div>" +
                         "</div>" +
                      "</div>";
    var closebtnTemplate = "<button type='button' class='close' data-dismiss='modal' aria-label='Close'>" +
                                "<span aria-hidden='true'>&times;</span>" +
                            "</button>";
    var oDialog =  $(template);
    if (option.opacity) {
        $(".modal-dialog", oDialog).css("opacity", option.opacity);
    }
    if (option.type) {
        if (option.type == "large") $(".modal-dialog", oDialog).addClass("modal-lg");
        if (option.type == "small") $(".modal-dialog", oDialog).addClass("modal-sm");
    }
    if (option.close != false) {
        $(".modal-header", oDialog).prepend(closebtnTemplate);
    }
    if (option.title) {
        $(".modal-title",oDialog).html(option.title);
    }
    if(option.title == false){
        $(".modal-header",oDialog).hide();
    }
    if (typeof(option.headerable) != "undefined" 
        && option.headerable == false) {
        $(".modal-header",oDialog).remove();
    }
    if (option.width) {
        $(".modal-dialog", oDialog).css("width", option.width);
    }
    $(control).show();
    $(".modal-content", oDialog).append(control);

    $(oDialog).on("shown.bs.modal", function(e) {
        WinUtil.hideObject();
        if (onshow) onshow(control,option,e);
    })

    $(oDialog).on("show.bs.modal", function(e) {
        if (onbeforeshow) onbeforeshow(control,option,e);
    })

    $(oDialog).on("hidden.bs.modal", function(e) {
        WinUtil.showObject();
        if (onclose) onclose(control,option,e);
    })

    $(oDialog).on("hide.bs.modal", function(e) {
        if (onbeforehide) onbeforehide(control,option,e);
    })

    $(oDialog).modal(option);
}

/**
 * 内蒙大屏 弹窗
 */
WinUtil.showScreenDialog = function (control, option, onshow, onclose,onbeforeshow,onbeforehide) {
    var title = option.title ? option.title : "操作";
    var type = option.dialogType ? option.dialogType : 1;   //  1 或者 2
    var text;
    if(type == 1){
        text = ' <div class="screen-comp open-dialog">\n' +
            '        <div class="top-iocn"/><div class="bottom-iocn"/><div class="left-iocn"/><div class="right-iocn"/>\n' +
            '        <div class="screen-body">\n' +
            '            <div class="screen-title">\n' +
            '                <span>'+title+'</span>\n' +
            '            </div>\n' +
            '            <div class="title-line"/>\n' +
            '            <div class="screen-content">'+
            '       </div>'+
            '       </div>';
    }else if(type==2){
        text = ' <div class="corner-comp-relative open-dialog">\n' +
            '      <div class="left-top-corner"/><div class="right-top-corner"/>\n' +
            '      <div class="left-bottom-corner"/><div class="right-bottom-corner"/>\n' +
            '      <div class="screen-content">\n' +
            '      </div>'
            ' </div>'
    }else{
        text = ' <div class="screen-comp corner-comp-relative open-dialog">\n' +
            '        <div class="screen-content">\n' +
            '        </div>'
            ' </div>'
    }

    var content = $(text)[0];
    $(control).show();
    $(".screen-content",content).html(control);
    option.title = false;
    WinUtil.openDialog(content,option, onshow, onclose,onbeforeshow,onbeforehide);
}

/**
 * 隐藏监控
 */
WinUtil.hideObject = function() {
    $(".video-content").each(function(e) {
        $("object", this).width(0);
        $("object", this).height(0);
    });
    $(".monitor-body").each(function(e) {
        $("object", this).width(0);
        $("object", this).height(0);
    });
}

/**
 * 显示监控
 */
WinUtil.showObject = function() {
    $(".video-content").each(function(e) {
        $("object", this).width($(this).width());
        $("object", this).height($(this).height());
    });
    $(".monitor-body .info").each(function(e) {
        $("object", this).width($(this).width());
        $("object", this).height($(this).height());
    });
}

/**
 * 对话框打开一个页面
 * @param src
 * @param option
 * @param onshow
 * @param onclose
 */
WinUtil.openPage = function(src, option, onshow, onclose,onbeforeshow,onbeforehide){
	var iframe = document.createElement("iframe");
    var height = 400;
    if (option.height) height = option.height;
	$(iframe).css({
		width:"100%",
        height:height,
		border:'0px solid #fff'
	});
	iframe.src = src;
	$(iframe).attr("frameborder","0");
	this.openDialog(iframe, option, onshow, onclose,onbeforeshow,onbeforehide);
}

/**
 * 关闭对话框
 */
WinUtil.closeDialog = function(){
    $(".modal").modal("hide");
}

/**
 * @param control 显示tip的控件
 * @param option
 *      - title: tip内容
 *      - trigger: 默认manual, "hover focus click"
 *      - time: 多少秒后关闭，默认5秒
 *      - placement: 默认top ["bottom","left","right"]
 *      - html:默认false 显示文字， true支持html显示
 *      - handleable: 默认false, 如果为true, 则点击tip外自动关闭tip.点击tip内不关闭tip.
 *          需要在点击控件加上handleable样式
 *      - delay: {hide:1000, show:1000} 延迟显示和延迟隐藏
 *      - viewport : 基于哪个html展示. 默认为body
 */
WinUtil.showTip = function(control, option) {
    $(control).tooltip(option);
    $(control).tooltip('show');
}

WinUtil.closeTip = function(control) {
    $(control).tooltip('hide');
}

WinUtil.destroyTip = function(control) {
    $(control).tooltip('destroy');
}


/**
 * @param control 显示pop的控件
 * @param option
 *      - title: pop标题
 *      - content: pop内容
 *      - trigger: 默认manual, "hover focus click"
 *      - time: 多少秒后关闭，默认不关闭
 *      - placement: 默认top ["bottom","left","right"]
 *      - html:默认false 显示文字， true支持html显示
 *      - handleable: 默认false, 如果为true, 则点击tip外自动关闭tip.点击tip内不关闭tip.
 *          需要在点击控件加上handleicon样式
 *      - delay: {hide:1000, show:1000} 延迟显示和延迟隐藏
 *      - viewport : 基于哪个html展示. 默认为body
 *      - offset : false
 *      - offsetLeft : 0 偏移量
 *      - showCallBack 显示弹窗回调事件
 *      - hideCallBck 关闭事件回调事件
 */
WinUtil.showPop = function(control, option,showCallBack,hideCallBck){
    if (!option.trigger) option.trigger = "manual";
    $(control).popover(option);
    $(control).popover("show");
    $(control).on('shown.bs.popover',function (e) {
        if(showCallBack) showCallBack(control,option,e);
    });
    $(control).on('hide.bs.popover',function (e) {//出发关闭立即调用事件
    	if(typeof(control.deletenotClose)!="undefined"){//在showPop当中的页面中如果有删除节点的动作（不管是jquery还是dom）都会引起关闭事件的产生原因不明，造成页面无故关闭，现通过增加一个属性的方式（需要使用此属性的页面设置）不让其关闭
    		delete control.deletenotClose;
    		return false;//阻止事件的继续传播
    	}else{
    		WinUtil.destroyObject(option.content);
        	if(hideCallBck) hideCallBck(control,option,e);	
    	}        
    });
}

/**
 * 关闭提示信息
 */
WinUtil.closePop = function(control) {
    $(control).popover("hide");
}

WinUtil.destroyPop = function(control) {
    $(control).popover('destroy');
}

/**
 *  清除空的弹出框
 */
WinUtil.clearPop = function() {
    $(".handleable").each(function(){
        var length = $(".popover-content", this).children().length;
        if (length == 0) {
            $(this).popover("destroy");
        }
    });
}

WinUtil.destroyObject = function (oControl) {
    $(".video-content",oControl).each(function(e) {
        Device.delVideoByObj(this);
    });
}

/**
 * 显示消息
 * @param {Object} oParam
 * oParam参数有 type,text,html,time
 * type 分为 error,warn,success,info  //默认info
 * text,html 只能选择其中一个，设置消息内容
 * time 是设置几秒钟自动关闭消息。不传该参数则由用户手动关闭消息
 */
WinUtil.showMessage = function(oParam){
	var html = WinUtil.createMessage();
	var sCTitle,sCPath 
	if(oParam.type == "error"){
		$(html).css("backgroundColor","#fd0505");
		sCTitle = "错误";
		sCPath = "./webapi/images/message/error.gif"
	}else if(oParam.type == "warn"){
		$(html).css("backgroundColor","#fd6b15");
		sCTitle = "警告";
		sCPath = "./webapi/images/message/warning.gif"
	}else if(oParam.type == "success"){
		$(html).css("backgroundColor","#2bb04e");
		sCTitle = "成功";
		sCPath = "./webapi/images/message/ok.gif"
	}else{
		sCTitle = "信息";
		sCPath = "./webapi/images/message/warn.gif"
	}
	if(oParam.text){
		$(".messagecontent",html).append(
                '<img class="cicon" src='+sCPath+'>'+
				'<span class="ctitle">'+sCTitle+'</span>'+
				'<span class=cbody>'+oParam.text+'</span>'
        );
	}else{
		if(oParam.html){
			$(".messagecontent", html).html(oParam.html);
		}
	}
	
	if(oParam.time){
		var sec = oParam.time/1000;
		this.setTime(html,sec);
	}
	
	$(".mclose", html).click(function(){
        WinUtil.closeMessage(html);
	});
	$("body").append(html);
	$(".message").animate({height:'show'},1000);
    return html;
}

WinUtil.setTime = function(html, time){
	$(".showtime",html).text(time);
	time = time - 1;
	if(time > 0 ){
		setTimeout(function(){
			WinUtil.setTime(html,time);
		},1000);
	} else {
        WinUtil.closeMessage(html);
	}
}

WinUtil.closeMessage = function(html) {
    if (html) {
        $(html).animate({height:'hide'}, 1000, function(){
            $(this).remove();
        });
    } else {
        $(".message").animate({height:'hide'}, 1000, function(){
            $(this).remove();
        });
    }
}

/**
 * 创建消息的HTML
 */
WinUtil.createMessage = function(){
	var gDiv = document.createElement("div"); //全局容器
	var tDiv = document.createElement("div"); //标题容器
	var cDiv = document.createElement("div"); //内容容器
	$(gDiv).addClass("message");
	if (!!window.ActiveXObject || "ActiveXObject" in window){
		var scrollTop = document.documentElement.scrollTop;
	}else{
		var scrollTop = document.body.scrollTop;
	}
	$(gDiv).css("bottom", -scrollTop);
	
	$(tDiv).addClass("messagetitle");
	$(cDiv).addClass("messagecontent");
	$(gDiv).append(tDiv);
	$(gDiv).append(cDiv);
	$(tDiv).append('<img class="micon" src="./webapi/images/message/message.gif"/> '+
				   '<span class="mtitle">提示信息</span>'                    +
				   '<img class="mclose" src="./webapi/images/message/close.gif"/>');
	$(gDiv).append('<span class="showtime"></span>');
	return gDiv;
}

/**
 * 增加页面阴影层
 */
WinUtil.pageAppendMask = function() {
    var maskDiv = document.createElement("div");
    maskDiv.id = "maskLayer";
    $("body").append(maskDiv);
    var clientHeight = document.documentElement.clientHeight;
    var scrollHeight = document.documentElement.scrollHeight;
    if (clientHeight < scrollHeight) {
        clientHeight = scrollHeight;
    }
    $(maskDiv).css({
        left:0,
        top:0,
        width:"100%",
        height:clientHeight,
        position:"absolute",
        zIndex:99990,
        backgroundColor:"#333"
    });
    $(maskDiv).fadeTo(0,0.3);
}

/**
 * 移除页面阴影层
 */
WinUtil.pageRemoveMask = function() {
    $($("#maskLayer","body")[0]).remove();
}

/**
 * 加载图标方法
 */
WinUtil.pageWaitingShow = function (oParam){
    WinUtil.pageAppendMask();
	var pageWaitingDiv = document.createElement("div");
	$(pageWaitingDiv).attr({id:"pageWaiting"});
    $(pageWaitingDiv).addClass("loading");
    //是否传递文字
    if(oParam && oParam.text){
        var text = oParam.text;
    }else{
        text = "加载中...";
    }
    $(pageWaitingDiv).append("<span>" + text + "</span>");
    $("body").append(pageWaitingDiv);

    //如果传递了left,top参数，则根据参数显示，否则居中当前页面显示
    var avaHeight = document.documentElement.clientHeight - $(pageWaitingDiv).height();
    var avaWidth = document.documentElement.clientWidth - $(pageWaitingDiv).width();
    if(oParam && oParam.left){
        var left = oParam.left;
    }else{
        var left = (avaWidth)/2;
    }
    if(oParam && oParam.top){
        var top = oParam.top;
    }else{
        var top = avaHeight/2
    }
    $(pageWaitingDiv).css("left", left);
    $(pageWaitingDiv).css("top", top);
}

/**
 * 隐藏
 */
WinUtil.pageWaitingHide = function(){
    WinUtil.pageRemoveMask();
	$("#pageWaiting").remove();
}

/**
 * 图片预览
 * oContainer  - 要预览图片的DIV HTML节点.
 *    如: <div><img src=''><img src=''></div>
 * options  - 参数
 */
WinUtil.imagePreview = function(oContainer, options) {
    //动态加载JS
    if (!$(oContainer).viewer) {
        $.ajax({async: false,
            cache: true,
            type: "GET",
            url: "/public.common/webapi/common/imageviewer/jquery-image-viewer.js",
            dataType: "script"
        });
    }
    $(oContainer).viewer(options);
}

/**
 * 组件根据分辨率自动方法缩小, 用于指挥中心大屏一个浏览器显示一个组件.
 * @param cw 组件固定宽度
 * @param ch 组件固定高度
 * @param obj 要放大缩小的id元素数组
 * @param othat 要放大缩小的id元素数组所在的组件
 */
WinUtil.adaptResolution = function(cw, ch,obj,othat) {
    var ah = document.documentElement.clientHeight;
    var aw = document.documentElement.clientWidth;
    //求差
    var dh = ah - ch;
    var dw = aw - cw;
    var isZoomOut = false;
    if (dh < 0 || dw < 0) isZoomOut = true;
    //求放大或缩小倍数
    dh = Math.abs(dh);
    dw = Math.abs(dw);
    var zoomWidth = (dw/cw).toFixed(2);
    var zoomHeight = (dh/ch).toFixed(2);
    var zoom = Math.min(zoomWidth, zoomHeight);
    if (!isZoomOut) {
    	//如果传入了放大节点，就放大传入的节点
    	if(obj){
    		for(var i = 0 ; i < obj.length ; i++){
    			$("#"+obj[i],othat.getHTML())[0].style.zoom = 1 + zoom;
    		}
    	}else{
    		document.body.style.zoom = 1 + zoom;
    	}
    }
    return 1 + zoom;
}
/**
 * 在页面中打开一个弹出框
 * @param message 弹出框提示内容
 * @param option
 *      - title 弹出框标题
 *      - keyboard 默认true,支持esc关闭对话框
 *      - backdrop 默认不支持遮罩层 [false:无遮罩层] ['static':有遮罩层，点击遮罩层外不关闭对话框]
 *      - top 距离页面顶部多少距离
 *      - color 按钮和标题的颜色
 */
WinUtil.alert = function(message,options) {
	var temp = "<div class='modal fade' id='alert_like' tabindex='-1' aria-hidden='true'>"+
					"<div class='modal-dialog modal-sm'>";
	if(options.openiframe == true){
		temp = temp+"<iframe frameBorder='0' marginWidth='0' marginHeight='0'"+
						"style='position:absolute;top:0px;left:0px;width:100%;height:100%;" +
						"z-index:-1;visibility:inherit;background-color:transparent;'>" +
					"</iframe>";
	}
	temp = temp+"<div class='modal-content'>"+
							"<div class='modal-header'>"+
								"<button class='close' data-dismiss='modal'><span>&times;</span></button>"+
								"<h5 class='modal-title' id='myModalLabel' style='color:#fff'></h5>"+
							"</div>"+
							"<div class='modal-body' style='font-size:15px;color:black;'>"+
							"</div>"+
							"<div class='modal-footer'>"+
			            		"<button id='ok_btn' class='btn btn-sm btn-primary' data-dismiss='modal'>确 定</button>"+
			            	"</div>" +
			            "</div>"+
			         "</div>"+
			      "</div>";
	var oDialog =  $(temp);
	if(!options){
		options = {};
	}
	if(!options.title){
		options.title = "提示"
	}
	if(!options.backdrop){
		options.backdrop = "static";
	}
	if(options.top){
		if(String(options.top).indexOf("px") == -1){
			options.top = options.top + "px";
		}
		$(oDialog).css("margin-top",options.top)
	}
	if(options.color){
		$(".modal-header", oDialog).css("background-color",options.color);
		$("#ok_btn", oDialog).removeClass("btn-primary");
		$("#ok_btn", oDialog).css("background-color",options.color);
	}
    $(oDialog).on("show.bs.modal", function(e) {
        WinUtil.hideObject();
    })
    $(oDialog).on("hidden.bs.modal", function(e) {
        WinUtil.showObject();
    })
	$("#myModalLabel", oDialog).text(options.title);
	$(".modal-body", oDialog).text(message);
	$(oDialog).modal(options);//设置弹窗的bootstrap属性方法
}
/**
 * 在页面中打开一个confirm框
 * @param message 弹出框提示内容
 * @param option
 *      - title 弹出框标题
 *      - keyboard 默认true,支持esc关闭对话框
 *      - backdrop 默认不支持遮罩层 [false:无遮罩层] ['static':有遮罩层，点击遮罩层外不关闭对话框]
 *      - top 距离页面顶部多少距离
 *      - color 按钮和标题的颜色
 *      - openiframe 是否开启iframe
 * @param callback 回调返回ture/false
 */
WinUtil.comfirm = function(message,options,callback) {
	var temp = "<div class='modal fade' id='alert_like' tabindex='-1' aria-hidden='true'>"+
					"<div class='modal-dialog modal-sm' style='margin: 0 auto;'>";
	if(options.openiframe == true){
		temp = temp+"<iframe frameBorder='0' marginWidth='0' marginHeight='0'"+
						"style='position:absolute;top:0px;left:0px;width:100%;height:100%;" +
						"z-index:-1;visibility:inherit;background-color:transparent;'>" +
					"</iframe>";
	}
	temp = temp+" <div class='modal-content'>"+
							"<div class='modal-header'>"+
								"<button class='close cancel' data-dismiss='modal'><span>&times;</span></button>"+
								"<h5 class='modal-title' id='myModalLabel' style='color:#fff'></h5>"+
							"</div>"+
							"<div class='modal-body'style='font-size:15px;color:black;'>"+
							"</div>"+
							"<div class='modal-footer'>"+
				        		"<button class='btn btn-sm btn-primary cancel' data-dismiss='modal'>取消</button>"+
				        		"<button class='btn btn-sm btn-primary ok' data-dismiss='modal'>确定</button>"+
				        	"</div>" +
				        "</div>"+
				     "</div>"+
				  "</div>";
	var oDialog =  $(temp);
	if(!options){
		options = {};
	}
	if(!options.title){
		options.title = "提示"
	}
	if(!options.backdrop){
		options.backdrop = "static";
	}
	if(options.top){
		if(String(options.top).indexOf("px") == -1){
			options.top = options.top + "px";
		}
		$(oDialog).css("margin-top",options.top);
	}
	if(options.width){
//		if(String(options.width).indexOf("px") == -1){
//			options.width = options.top + "px";
//		}
		$(".modal-dialog",oDialog).width(options.width);
	}
	if(options.color){
		$(".modal-header", oDialog).css("background-color",options.color);
		$(".btn-sm", oDialog).removeClass("btn-primary");
		$(".btn-sm", oDialog).css("background-color",options.color);
	}
	$("#myModalLabel", oDialog).text(options.title);
	$(".modal-body", oDialog).text(message);
    $(oDialog).on("show.bs.modal", function(e) {
        WinUtil.hideObject();
    })
	$(oDialog).find(".ok").on("click",function(){
	    WinUtil.showObject();
		if(callback) callback(true);
    })
    $(oDialog).find(".cancel").on("click",function(){
        WinUtil.showObject();
    	if(callback) callback(false);
    })
	$(oDialog).modal(options);//设置弹窗的bootstrap属性方法
}

/**
 * 选项卡打开一个方案
 * @param name
 * @param planid
 * @param param 页面参数, js对象
 */
WinUtil.openPlan = function(name, pageid, param) {
    if (!param) {
        param = {};
    }
    param.pageid = pageid;
    application.postMessage({
        id:"MSG_Main_OpenPage",
        title:name,
        path:"/public.system/comp/page/appview/AppView.html",
        params:param
    });
}